/* 接收端代码 receive.c */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <signal.h>

#define GROUP_IP "224.0.0.1"    // 组播组IP地址
#define PORT 8765               // 端口号
#define LOCAL_IP "127.0.0.1" // 本地IP地址

int sockfd;
struct ip_mreq group;
struct sigaction act;

void handler_signal(int signal)
{
    printf("signal=%d \n", signal);
    // if (signal == SIGINT)
    {
        // 离开组播组
        if (setsockopt(sockfd, IPPROTO_IP, IP_DROP_MEMBERSHIP, &group, sizeof(group)) < 0)
        {
            perror("setsockopt failed");
            exit(EXIT_FAILURE);
        }
        close(sockfd);
    }

    exit(0);
}

void signal_init()
{
    act.sa_handler = handler_signal;
    sigemptyset(&act.sa_mask);
    act.sa_flags = 0;
    sigaction(SIGINT, &act, 0);
}

int main()
{
    struct sockaddr_in local_addr, sender_addr;
    socklen_t sender_addr_len = sizeof(sender_addr);
    char buffer[1024];
    signal_init();

    // 创建UDP套接字
    if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
    {
        perror("socket creation failed");
        exit(EXIT_FAILURE);
    }

    // 设置套接字选项，允许地址重用
    int reuse = 1;
    if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)) < 0)
    {
        perror("setsockopt failed");
        exit(EXIT_FAILURE);
    }

    // 绑定本地地址和端口
    memset(&local_addr, 0, sizeof(local_addr));
    local_addr.sin_family = AF_INET;
    local_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    local_addr.sin_port = htons(PORT);

    if (bind(sockfd, (struct sockaddr *)&local_addr, sizeof(local_addr)) < 0)
    {
        perror("bind failed");
        exit(EXIT_FAILURE);
    }

    // 加入组播组
    group.imr_multiaddr.s_addr = inet_addr(GROUP_IP);
    group.imr_interface.s_addr = htonl(INADDR_ANY);

    if (setsockopt(sockfd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &group, sizeof(group)) < 0)
    {
        perror("setsockopt failed");
        exit(EXIT_FAILURE);
    }

    while (1)
    {
        printf("Waiting for multicast messages...\n");
        // 接收组播消息
        ssize_t recv_len = recvfrom(sockfd, buffer, sizeof(buffer) - 1, 0,
                                    (struct sockaddr *)&sender_addr, &sender_addr_len);
        if (recv_len < 0)
        {
            perror("recvfrom failed");
            exit(EXIT_FAILURE);
        }

        buffer[recv_len] = '\0';
        printf("Received from %s:%d: %s\n",
               inet_ntoa(sender_addr.sin_addr), ntohs(sender_addr.sin_port), buffer);
    }

    // 离开组播组
    if (setsockopt(sockfd, IPPROTO_IP, IP_DROP_MEMBERSHIP, &group, sizeof(group)) < 0)
    {
        perror("setsockopt failed");
        exit(EXIT_FAILURE);
    }
    close(sockfd);
    sockfd = -1;

    return 0;
}